#include <QDebug>
#include <QColor>
#include "StarlabMainWindow.h"
#include "CmdLineParser.h"
#include "StarlabApplication.h"
#include "StarlabSettings.h"
#include <QGLFormat>

int main_(int argc, char *argv[]) { 
    /// Create a starlab application
    StarlabApplication application(argc,argv);
    /// Creates / loads pre-existing settings
    StarlabSettings settings;
    /// Parse command line into StarlabSettings
    CmdLineParser(argc,argv,settings);     
        
    //qDebug() << qPrintable(settings);
    
    // Anti-aliasing when using QGLWidget or subclasses
    QGLFormat glf = QGLFormat::defaultFormat();
    glf.setSamples(8);
    QGLFormat::setDefaultFormat(glf);

    /// Lists filters if requested
    if(settings.getString("action")=="list-filters"){
        qDebug() << "Available filters: ";
        foreach(FilterPlugin* p, application.plugins.filterPlugins.values())
            qDebug() << "  " << qPrintable( p->name() );
        exit(0);        
    }
    /// Create window (@note *new* is important)
    StarlabMainWindow* mainWindow = new StarlabMainWindow(application, settings);        
    
    /// @todo Automatically load layer menu if I opened more than one model    
    // if(mainWindow->document()->models.size()>=2)
    //    emit mainWindow->show_layer_dialog(true);    

    /// Loads the input models
    QStringList inputs = settings.getStringList("inputs");
    foreach(QString file, inputs)
        if( !application.load(file) )
            qDebug() << "Load of " + file + " failed (missing plugin for requested filter? or missing gui_filterplugins?)";
    mainWindow->drawArea()->resetView();
    mainWindow->update();
    
    /// Shows a filter GUI if it has one specified in its settings
    QString filterName = settings.getString("filter");
    if(!filterName.isEmpty()) mainWindow->triggerFilterByName(filterName);

    /// Starts the event loop
    return application.exec();    
}

int main(int argc, char *argv[]){
    try{
        return main_(argc, argv);
    } catch(std::exception& e) {
        qDebug() << e.what();
        return -1;
    } catch(...) {
        qDebug() << "BAD EXCEPTION";
        return -1;
    }
}
